<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增种植区域</el-button>
        <!-- <el-button v-auth="'batchAdd'" type="primary" :icon="Upload" plain @click="batchAdd">批量添加用户</el-button> -->
        <el-button v-auth="'export'" type="primary" :icon="Download" plain @click="webDerive">导出种植区域数据</el-button>
        <!-- <el-button type="primary" plain @click="toDetail">To 子集详情页面</el-button> -->
        <!-- <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedListIds)">
          批量删除用户
        </el-button> -->
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- nameHeader -->
      <!-- <template #nameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template> -->
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <UserDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
// import { useRouter } from "vue-router";
import { Tree } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
// import { useDownload } from "@/hooks/useDownload";
// import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/proTable/components/UserDrawer.vue";
// HeaderRenderScope
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
// Refresh，Upload
import { CirclePlus, Delete, EditPen, Download, View } from "@element-plus/icons-vue";
import {
  getAreaList,
  deleteArea,
  editArea,
  addArea
  // changeUserStatus,
  // resetUserPassWord,
  // exportUserInfo
  // BatchAddUser,
  // getUserStatus
  // getUserGender
} from "@/api/modules/area";
import { userStatus } from "@/utils/dict";
// import * as XLSX from "XLSX";
import { exportExcel } from "@/utils/ExportExcel";

// const router = useRouter();

// 跳转详情页
// const toDetail = () => {
//   router.push(`/proTable/useProTable/detail/${Math.random().toFixed(3)}?params=detail-page`);
// };

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && page && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  console.log(data, "data");
  return {
    list: data.data,
    total: data.total,
    page: data.page,
    pageSize: data.pageSize
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getAreaList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  // newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  // newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  // delete newParams.createTime;
  params.page || (newParams.page = 1);
  params.pageSize || (newParams.pageSize = 10);
  console.log(params, "params");
  console.log(getAreaList(newParams), "get");
  return getAreaList(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
// const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
// const headerRender = (scope: HeaderRenderScope<Tree.ResAreaList>) => {
//   return (
//     <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
//       {scope.column.label}
//     </el-button>
//   );
// };

// 表格配置项
const columns = reactive<ColumnProps<Tree.ResAreaList>[]>([
  // { type: "selection", fixed: "left", width: 70 },
  // { type: "sort", label: "排序", width: 80 },
  {
    type: "index",
    label: "索引",
    width: 85
  }, //
  { type: "expand", label: "展开", width: 85 }, //
  // {
  //   prop: "name",
  //   label: "序号",
  //   width: 96
  // },
  {
    prop: "name",
    label: "区域名称",
    search: { el: "input" },
    width: 136
  },
  // {
  //   prop: "gender",
  //   label: "性别",
  //   // 字典数据（本地数据）
  //   enum: genderType,
  //   // 字典请求不带参数
  //   // enum: getUserGender,
  //   // 字典请求携带参数
  //   // enum: () => getUserGender({ id: 1 }),
  //   search: { el: "select", props: { filterable: true } },
  //   fieldNames: { label: "label", value: "value" }
  // },
  // {
  //   // 多级 prop
  //   prop: "Tree.detail.age",
  //   label: "年龄",
  //   search: {
  //     // 自定义 search 显示内容
  //     render: ({ searchParam }) => {
  //       return (
  //         <div class="flx-center">
  //           <el-input vModel_trim={searchParam.minAge} placeholder="最小年龄" />
  //           <span class="mr10 ml10">-</span>
  //           <el-input vModel_trim={searchParam.maxAge} placeholder="最大年龄" />
  //         </div>
  //       );
  //     }
  //   }
  // },
  { prop: "latitude", label: "纬度", search: { el: "input" } },
  { prop: "longitude", label: "经度", search: { el: "input" } },
  {
    prop: "sort",
    label: "排序",
    search: { el: "input" },
    sortable: true // 排序
  },
  { prop: "memo", label: "备注", search: { el: "input" } },
  // {
  //   prop: "status",
  //   label: "状态",
  //   // enum: getUserStatus,
  //   enum: userStatus,
  //   search: { el: "tree-select", props: { filterable: false } }, // 可输入筛选
  //   fieldNames: { label: "label", value: "value" },
  //   render: scope => {
  //     return (
  //       <>
  //         {BUTTONS.value.status ? (
  //           <el-switch
  //             model-value={scope.row.status}
  //             active-text={scope.row.status ? "启用" : "禁用"}
  //             active-value={1}
  //             inactive-value={0}
  //             onClick={() => changeStatus(scope.row)}
  //           />
  //         ) : (
  //           <el-tag type={scope.row.status ? "success" : "danger"}>{scope.row.status ? "启用" : "禁用"}</el-tag>
  //         )}
  //       </>
  //     );
  //   }
  // },
  {
    prop: "status",
    label: "状态",
    tag: true,
    sortable: true, // 排序
    enum: userStatus,
    search: { el: "tree-select" },
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "created_at",
    label: "创建时间",
    // headerRender,
    width: 180,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
      // defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
      // defaultValue: [null]
    },
    sortable: true // 排序
  },
  {
    prop: "updated_at",
    label: "更新时间",
    // headerRender,
    width: 180,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
      // defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
      // defaultValue: [null]
    },
    sortable: true // 排序
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 删除用户信息
const deleteAccount = async (params: Tree.ResAreaList) => {
  await useHandleData(deleteArea, { id: [params.id] }, `删除【${params.name}】种植区域`);
  proTable.value?.getTableList();
};

// 格到本地xlsx文件 ----
const webDerive = () => {
  ElMessageBox.confirm("是否确认导出选中数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    //deleteDate  选中数据列表
    let titleArr = ["序号", "区域名称", "纬度", "经度", "创建时间", "更新时间", "状态"];
    const oldTableData = JSON.parse(JSON.stringify(proTable.value?.tableData));
    const filterVal = ["index", "name", "latitude", "longitude", "created_at", "updated_at", "status"];
    const newTableData = oldTableData.map((v, i) =>
      filterVal.map(j => {
        if (j === "index") {
          return i;
        } else if (j === "status") {
          return v[j] === 0 ? "禁用" : "正常";
        } else {
          return v[j];
        }
      })
    );
    const item = oldTableData[0];
    console.log(newTableData, "newTableData");
    const title = `${item.name} - ${new Date().toLocaleString().replaceAll("/", "-")}`;
    exportExcel({
      json: newTableData, //数据
      name: title, //表名
      titleArr: titleArr, //表头
      sheetName: "sheet" //页签
    });
  });
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
// const batchAdd = () => {
//   const params = {
//     title: "用户",
//     tempApi: exportUserInfo,
//     importApi: BatchAddUser,
//     getTableList: proTable.value?.getTableList
//   };
//   dialogRef.value?.acceptParams(params);
// };

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Tree.ResAreaList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addArea : title === "编辑" ? editArea : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
@/utils/ExportExcel
